const db = require('../config/db');

class Admin {
  static async findByEmail(email) {
    const [rows] = await db.query('SELECT * FROM admins WHERE email = ?', [email]);
    return rows.length ? rows[0] : null;
  }

  static async create(admin) {
    const [result] = await db.query(
      'INSERT INTO admins (username, email, password, is_super_admin) VALUES (?, ?, ?, ?)',
      [admin.username, admin.email, admin.password, admin.is_super_admin || 0]
    );
    return result.insertId;
  }

  static async findById(id) {
    const [rows] = await db.query("SELECT * FROM admins WHERE id = ?", [id]);
    return rows.length ? rows[0] : null;
  }

  static async update(id, updateData) {
    const fields = [];
    const params = [];
    if (updateData.username !== undefined) {
      fields.push("username = ?");
      params.push(updateData.username);
    }
    if (updateData.email !== undefined) {
      fields.push("email = ?");
      params.push(updateData.email);
    }
    if (updateData.password !== undefined) {
      fields.push("password = ?");
      params.push(updateData.password);
    }
    if (fields.length === 0) return false;
    const query = `UPDATE admins SET ${fields.join(", ")} WHERE id = ?`;
    params.push(id);
    const [result] = await db.query(query, params);
    return result.affectedRows > 0;
  }
}

module.exports = Admin;